<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Str;
use App\Models\Category;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Tag;
use App\Services\PostService;

/**
 * 后台文章管理控制器
 * 
 * 职责：
 * - 处理后台文章管理相关的HTTP请求
 * - 调用服务层处理业务逻辑
 * - 统一响应格式
 */
class PostController extends Controller
{
    /**
     * 文章服务
     * 
     * @var PostService
     */
    protected PostService $postService;

    /**
     * 构造器
     */
    public function __construct(PostService $postService)
    {
        $this->postService = $postService;
    }

    /**
     * 显示文章列表
     * 
     * @param Request $request
     * @return \Inertia\Response
     */
    public function index(Request $request)
    {
        // 获取过滤条件
        $filters = $request->only([
            'search',
            'status',
            'category',
            'tag',
            'date_from',
            'date_to',
            'min_views',
            'max_views',
            'min_likes',
            'max_likes',
            'sort'
        ]);

        // 调用服务层获取文章列表
        $posts = $this->postService->getAdminPosts($filters, 10);

        // 获取统计数据
        $stats = [
            'total' => Post::count(),
            'published' => Post::whereNotNull('published_at')->count(),
            'draft' => Post::whereNull('published_at')->count(),
            'total_views' => Post::sum('views'),
            'total_likes' => DB::table('post_likes')->count(),
            'total_comments' => DB::table('comments')->count(),
            'categories' => Category::withCount('posts')
                ->orderByDesc('posts_count')
                ->limit(5)
                ->get()
                ->map(fn($category) => [
                    'name' => $category->name,
                    'count' => $category->posts_count
                ]),
            'authors' => User::withCount('posts')
                ->orderByDesc('posts_count')
                ->limit(5)
                ->get()
                ->map(fn($author) => [
                    'name' => $author->name,
                    'count' => $author->posts_count
                ]),
            'tags' => Tag::withCount('posts')
                ->orderByDesc('posts_count')
                ->limit(10)
                ->get()
                ->map(fn($tag) => [
                    'name' => $tag->name,
                    'count' => $tag->posts_count
                ]),
            'trends' => Post::selectRaw('DATE(published_at) as date, COUNT(*) as count')
                ->whereNotNull('published_at')
                ->groupBy('date')
                ->orderBy('date', 'desc')
                ->limit(30)
                ->get()
                ->map(fn($item) => [
                    'date' => $item->date,
                    'count' => $item->count
                ]),
            'engagement' => [
                'avg_views' => Post::avg('views'),
                'avg_likes' => DB::table('post_likes')
                    ->selectRaw('COUNT(*) / COUNT(DISTINCT post_id) as avg_likes')
                    ->first()->avg_likes ?? 0,
                'avg_comments' => DB::table('comments')
                    ->selectRaw('COUNT(*) / COUNT(DISTINCT post_id) as avg_comments')
                    ->first()->avg_comments ?? 0,
            ],
        ];

        return Inertia::render('Admin/Posts/Index', [
            'posts' => [
                'data' => $posts->map(function ($post) {
                    return [
                        'id' => $post->id,
                        'title' => $post->title,
                        'slug' => $post->slug,
                        'excerpt' => Str::limit($post->excerpt, 80),
                        'content' => $post->content,
                        'author' => [
                            'name' => $post->author->name,
                        ],
                        'category' => $post->category ? [
                            'name' => $post->category->name,
                        ] : null,
                        'status' => $post->status,
                        'published_at' => $post->published_at,
                        'views' => $post->views,
                        'likes_count' => $post->likes_count,
                        'comments_count' => $post->comments_count,
                    ];
                }),
                'meta' => [
                    'current_page' => $posts->currentPage(),
                    'from' => $posts->firstItem(),
                    'last_page' => $posts->lastPage(),
                    'links' => $posts->linkCollection()->toArray(),
                    'path' => $posts->path(),
                    'per_page' => $posts->perPage(),
                    'to' => $posts->lastItem(),
                    'total' => $posts->total(),
                ],
            ],
            'filters' => $filters,
            'stats' => $stats,
        ]);
    }

    /**
     * 重定向到作者管理端创建文章
     */
    public function create()
    {
        return redirect()->route('author.posts.create');
    }

    /**
     * 重定向到作者管理端创建文章
     */
    public function store(Request $request)
    {
        return redirect()->route('author.posts.create');
    }

    /**
     * 显示文章详情
     * 
     * @param Post $post
     * @return \Inertia\Response
     */
    public function show(Post $post)
    {
        // 调用服务层获取文章详情
        $postData = $this->postService->getAdminPostDetail($post);

        return Inertia::render('Admin/Posts/Show', [
            'post' => $postData,
        ]);
    }

    /**
     * 重定向到作者管理端编辑文章
     */
    public function edit(Post $post)
    {
        return redirect()->route('author.posts.edit', $post->slug);
    }

    /**
     * 重定向到作者管理端更新文章
     */
    public function update(Request $request, Post $post)
    {
        return redirect()->route('author.posts.edit', $post->slug);
    }

    /**
     * 删除文章
     * 
     * @param Post $post
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Post $post)
    {
        try {
            // 调用服务层删除文章
            $this->postService->delete($post, auth()->user());

            return redirect()
                ->route('admin.posts.index')
                ->with('success', '文章删除成功！');
        } catch (\Exception $e) {
            return back()->with('error', '删除失败：' . $e->getMessage());
        }
    }

    public function trash(Request $request)
    {
        $query = Post::onlyTrashed()
            ->with(['author', 'category'])
            ->when($request->search, function ($query, $search) {
                $query->where('title', 'like', "%{$search}%")
                    ->orWhere('content', 'like', "%{$search}%");
            })
            ->when($request->sort, function ($query, $sort) {
                [$column, $direction] = explode(',', $sort);
                $query->orderBy($column, $direction);
            }, function ($query) {
                $query->latest('deleted_at');
            });

        $posts = $query->paginate(10);

        return Inertia::render('Admin/Posts/Trash', [
            'posts' => [
                'data' => $posts->map(function ($post) {
                    return [
                        'id' => $post->id,
                        'title' => $post->title,
                        'slug' => $post->slug,
                        'excerpt' => Str::limit($post->excerpt, 80),
                        'author' => [
                            'name' => $post->author->name,
                        ],
                        'category' => $post->category ? [
                            'name' => $post->category->name,
                        ] : null,
                        'deleted_at' => $post->deleted_at,
                    ];
                }),
                'meta' => [
                    'current_page' => $posts->currentPage(),
                    'from' => $posts->firstItem(),
                    'last_page' => $posts->lastPage(),
                    'links' => $posts->linkCollection()->toArray(),
                    'path' => $posts->path(),
                    'per_page' => $posts->perPage(),
                    'to' => $posts->lastItem(),
                    'total' => $posts->total(),
                ],
            ],
            'filters' => [
                'search' => $request->search,
                'sort' => $request->sort,
            ],
        ]);
    }

    public function restore($id)
    {
        try {
            $post = Post::onlyTrashed()->findOrFail($id);
            $post->restore();
            
            return back()->with('success', '文章已恢复！');
        } catch (\Exception $e) {
            return back()->with('error', '恢复失败：' . $e->getMessage());
        }
    }

    public function forceDelete($id)
    {
        try {
            $post = Post::onlyTrashed()->findOrFail($id);
            $post->forceDelete();
            
            return back()->with('success', '文章已永久删除！');
        } catch (\Exception $e) {
            return back()->with('error', '删除失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除文章
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function batchDestroy(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:posts,id'
        ]);

        // 调用服务层批量删除
        $count = $this->postService->batchDelete($validated['ids'], auth()->user());

        return back()->with('success', "已将 {$count} 篇文章移到回收站");
    }

    /**
     * 批量发布文章
     */
    public function batchPublish(Request $request) 
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:posts,id'
        ]);

        Post::whereIn('id', $validated['ids'])->update([
            'status' => 'published',
            'published_at' => now()
        ]);

        return back()->with('success', '已发布选中的文章');
    }

    /**
     * 批量移到回收站
     */
    public function batchTrash(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:posts,id'
        ]);

        Post::whereIn('id', $validated['ids'])->delete();

        return back()->with('success', '已将选中的文章移到回收站');
    }

    /**
     * 复制文章
     * 
     * @param Post $post
     * @return \Illuminate\Http\RedirectResponse
     */
    public function duplicate(Post $post)
    {
        try {
            // 调用服务层复制文章
            $newPost = $this->postService->duplicate($post);

            return redirect()
                ->route('admin.posts.edit', $newPost)
                ->with('success', '文章已复制！');
        } catch (\Exception $e) {
            return back()->with('error', '复制失败：' . $e->getMessage());
        }
    }

    /**
     * 切换文章发布状态
     * 
     * @param Post $post
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toggleStatus(Post $post)
    {
        try {
            // 调用服务层切换状态
            $updatedPost = $this->postService->toggleStatus($post);
            
            $message = $updatedPost->published_at ? '文章已发布' : '文章已设为草稿';
            
            return back()->with('success', $message);
        } catch (\Exception $e) {
            return back()->with('error', '状态更新失败：' . $e->getMessage());
        }
    }
}
